package storage

import (
    "cing.io/cing/pkg/util"
    "context"
    "fmt"
    "strings"

    clientv3 "go.etcd.io/etcd/client/v3"
    "google.golang.org/protobuf/proto"

    "cing.io/cing-api/core"
)

func getPlanLogKey(taskFullName string, planLogType core.PlanLog_Type, timestamp int64) string {
    return fmt.Sprintf("%s/%s/%d/%d", planLogPrefix, taskFullName, planLogType, timestamp)
}

func PutPlanLog(taskFullName string, planLogType core.PlanLog_Type, timestamp int64, msg string) error {
    key := getPlanLogKey(taskFullName, planLogType, timestamp)

    log := &core.PlanLog{Message: msg}

    bytes, err := proto.Marshal(log)
    if err != nil {
        return err
    }

    _, err = Etcd().Put(context.TODO(), key, string(bytes))
    if err != nil {
        return err
    }

    return nil
}

func GetLastCreatePlanLogKey(taskFullName string) (string, error) {
    key := fmt.Sprintf("%s/%s/%d/", planLogPrefix, taskFullName, core.PlanLog_CREATE)

    resp, err := Etcd().Get(context.TODO(), key, append(WithPrefixEnd(), clientv3.WithKeysOnly())...)
    if err != nil {
        return "", err
    }

    bytes := resp.Kvs[0].Key
    return string(bytes), nil
}

func GetPlanLastCreateTime(taskFullName string) (int64, error) {
    lastKey, err := GetLastCreatePlanLogKey(taskFullName)
    if err != nil {
        return 0, err
    }

    index := strings.LastIndex(lastKey, "/")
    timestamp, err := util.Str2int64WithError(lastKey[index+1:])
    if err != nil {
        return 0, err
    }

    return timestamp, nil
}
